var $contactTableList = $('#contactList');
var date = new Date();
var year = date.getFullYear();
// 0-超管 1-普通管理员
var isAdmin = $('#isAdmin').val();

$(function () {
    selectTime("all");

    $('select').selectpicker();


    $('#screenBox').on('show.bs.collapse', function () {
        $(this).next('p').find('a').html('<i class="mdi mdi-chevron-double-up"></i>收起');
    }).on('hide.bs.collapse', function () {
        $(this).next('p').find('a').html('<i class="mdi mdi-chevron-double-down"></i>展开');
    });

    $('#contactCategory').on('changed.bs.select', function (event, clickedIndex, isSelected, previousValue) {
        switch (clickedIndex) {
            case 0:
                searchCustomerPoolList(this, 7);
                break;
            case 1:
                searchCustomerPoolList(this, 7,'1')
                break;
            case 2:
                searchCustomerPoolList(this, 7,'2')
                break;
            case 3:
                searchCustomerPoolList(this, 8,'0')
                break;
        }
    })

    /* $('#test').selectpicker();
     $(document).on('click', '.dropdown-menu li:last-child a', function (e) {
         e.stopPropagation();
         e.preventDefault();
         var inputNode = '<input type="text"><button>新增</button>'
         $(this).parent().siblings('li').removeClass('selected, active');
         $(this).parent().html(inputNode);

     })
     $('#test li').on('shown.bs.select', function (e, clickedIndex, isSelected, previousValue) {

         /!*var choseVal = $(this).find('option').eq(clickedIndex).val();
         if (choseVal == 'add') {

         }*!/
     });
 */
    $contactTableList.bootstrapTable({
        classes: 'table contact-table',
        url: '/contact/contactList',                            // 请求地址
        method: 'post',                                         // 请求方式
        contentType: "application/x-www-form-urlencoded",       // 请求内容类型
        dataType: "json",                                       // 数据类型
        striped: true,                                          // 是否显示行间隔色
        sortable: true,                                         // 是否启用排序
        sortOrder: "desc",                                      // 排序方式
        sortName: 'createTm',                                   // 排序字段
        cache: false,                                           // 是否使用缓存
        showColumns: false,                                     // 显示隐藏列
        showRefresh: false,                                     // 显示刷新按钮
        showToggle: false,                                      // 切换显示样式
        showFooter: false,                                      // 显示Table脚部
        pagination: true,                                       // 是否显示分页
        showPaginationSwitch: false,                            // 是否显示分页按钮
        clickToSelect: true,                                    // 是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,                                 // 最少要显示的列数
        undefinedText: '',                                      // cell没有值时显示
        sidePagination: "server",                               // 分页方式：client客户端分页，server服务端分页
        uniqueId: 'productActivityId',
        idField: 'productActivityId',
        pageSize: globalPageSize,                                            // 每页的记录行数
        pageNumber: 1,                                          // 初始化加载第1页，默认第1页
        pageList: globalPageList,                            // 可供选择的每页的行数
        queryParams: queryParams,                               // 查询参数
        columns: [
            {title: '联系人ID', field: 'contactId', visible: false},
            {title: '', field: 'accessUrl', align: 'left', valign: 'middle', width: '100', formatter: contactTableList.head},
            {title: '联系人姓名', field: 'contactName', align: 'left', valign: 'middle', width: '', formatter: contactTableList.info},
            /*{title: '联系人职务', field: 'contactPosition', align: 'left', valign: 'middle', width: ''},
            {title: '所属公司', field: 'companyName', align: 'left', valign: 'middle', width: ''},
            {title: '联系人性质', field: 'contactNature', align: 'left', valign: 'middle', width: ''},*/
            {title: '最近跟进时间', field: 'followTm', align: 'left', valign: 'middle', width: '', formatter: contactTableList.lastTime},
            {title: '标签', field: 'tag', align: 'left', valign: 'middle', width: '', formatter: contactTableList.tag},
            {title: '操作', field: '', align: 'right', valign: 'middle', width: '', formatter: contactTableList.operation},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
            // $("[data-toggle='tooltip']").tooltip();
            $(document).on('mouseenter', '.contact-header', function () {
                var $this = $(this);
                var scrollTop = $(document).scrollTop();
                var tLeft = $(this).offset().left;
                var tTop = $(this).offset().top;

                $this.removeClass('hide-action');
                $this.css('z-index', '10').find('.action').css({
                    position: 'fixed',
                    left: tLeft + 38,
                    top: tTop - scrollTop - 29,
                });
                $(document).scroll(debounce(function () {
                    $this.addClass('hide-action');
                }, 200, true));
            }).on('mouseleave', '.contact-header', function () {
                $(this).css('z-index', '1')
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
        /*onResetView: function () {
        }*/
    });

    /*$(document).on('scroll', function () {
    })*/


});

function headAction (scrollTop) {
    for (var i = 0; i < 5; i++) {
        var element = 'index-' + i;
        var headNode = document.getElementById('element');
        var headNav = headNode.querySelector('.action');
        var pos = headNode.getBoundingClientRect();
        headNav.style.left = pos.x + pos.width / 2;
        headNav.style.top = pos.y + pos.width / 2;
    }
}

function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序
    params.bs = '0';
    //产品列表搜索条件
    return params;
}

data = {
    pageIndex: 1,  //页码
    pageSize: 5,  //分页大小
    sortName: "createTm",  //排序列名字
    sortOrder: "desc",  //排序规则(asc/desc)
    bs: "0",  //标识  0管理端 1用户端
    dateType: $("#dateType").val()
};
function queryParamsMoth(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序
    params.bs = '0';

    params.dateType= $("#dateType").val()
    //产品列表搜索条件
    return params;
}

function queryParamsSeach(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序
    // params.bs = '0';

    //产品列表搜索条件
    return params;
}


/**
 * 功能：联系人列表自定义内容
 * */
var contactTableList = {
    head: function (value, row, index, field) {
        // var imgNode = value ? ('<img src="' + row.accessUrl + '" alt="">') : row.contactName.split('')[0];
        var imgNode;
        // 解决联系人姓名为null报错的问题
        if (value) {
            imgNode = '<img src="' + row.accessUrl + '" alt="">';
        } else {
            row.contactName ? imgNode = row.contactName.split('')[0] : imgNode = '';
        }

        var headNode;
        if (row.abolishState == 1) {
            // 启用联系人
            headNode = '<div id="head-' + index +'" class="contact-header">' +
                '<a href="javaScript:void(0);">' + imgNode + '</a>' +
                '<div class="action">' +
                '<ul><li><a href="javaScript:void(0);" onclick="callCenter(\'' + row.customerId + '\')" title="线上电话"><i class="mdi mdi-headphones"></i></a></li>' +
                '<li><a href="javaScript:void(0);" onclick="goOnline(\'' + row.customerId + '\', \'' + row.contactId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'拜访\', );" title="拜访"><i class="mdi mdi-glassdoor"></i></a></li>' +
                '<li><a href="javaScript:void(0);" onclick="goOnline(\'' + row.customerId + '\', \'' + row.contactId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'微信交流\', );" title="微信交流"><i class="mdi mdi-wechat"></i></a></li>' +
                '<li><a href="javaScript:void(0);" onclick="goOnline(\'' + row.customerId + '\', \'' + row.contactId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'线下电话\', );" title="线下电话"><i class="mdi mdi-phone"></i></a></li>' +
                '<li><a href="javaScript:void(0);" onclick="goOnline(\'' + row.customerId + '\', \'' + row.contactId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'电子邮件\', );" title="电子邮件"><i class="mdi mdi-email-variant"></i></a></li>' +
                '<li><a href="javaScript:void(0);" onclick="goOnline(\'' + row.customerId + '\', \'' + row.contactId + '\', \'' + row.contactName + '\', \'' + row.contactInformation + '\', \'陪访\', );" title="陪访"><i class="mdi mdi-account-multiple"></i></a></li></ul></div></div>';
        } else if (row.abolishState == 2) {
            // 废止联系人
            headNode = '<div id="head-' + index +'" class="contact-header"><a href="javaScript:void(0);" class="abolish">' + imgNode + '</a><i class="mdi mdi-do-not-disturb"></i></div>';
        }
        return headNode;
    },
    info: function (value, row, index, field) {
        // 联系人职务: 0 公司管理 1 财务 2 人力 3 其他
        var contactPosition;
        switch (row.contactPosition) {
            case '0':
                contactPosition = '公司管理';
                break;
            case '1':
                contactPosition = '财务';
                break;
            case '2':
                contactPosition = '人力';
                break;
            default:
                contactPosition = '其他';
                break;
        }

        var name = value;                                                     // 联系人姓名
        var companyName = row.customerName || '-';                            // 客户名称
        var contactNature = row.contactNature ? '个人联系人' : '企业联系人';      // 联系人性质

        var html = '<div class="info"><h5><a href="JavaScript:void(0);" onclick="contactDetail(\'' + row.contactId + '\')">' + name + '</a><span>' + contactPosition + '</span><span>' + contactNature + '</span>';
        if (row.membershipLevel) {
            html += '<span class="vip">VIP' + row.membershipLevel + '</span>';
        }
        if(row.contactNature == 0) {
            html += '</h5><p><a href="JavaScript:void(0);" onclick="customerDetail(\'' + row.customerId + '\')">' + companyName + '</a></p></div>';
        }else{
            if(row.companyName == null) {
                html += '</h5><p><a href="JavaScript:void(0);">-</a></p></div>';
            }else {
                html += '</h5><p><a href="JavaScript:void(0);">' + row.companyName + '</a></p></div>';
            }
        }

        return html;
    },
    lastTime: function (value, row, index, field) {
        var html;
        if (value) {
            var followTime = new Date(value).Format("yyyy-MM-dd");
            //var timeArr = followTime.split(' ');
            //html = '<div class="time">' + timeArr[0] + '<span>' + timeArr[1] + '</span></div>';
            html = '<div class="time">' + followTime + '</div>';
        } else {
            html = '暂无跟进记录';
        }
        return html;
    },
    tag: function (value, row, index, field) {
        var html = '';
        if (value) {
            var tagsArr = value.split(',');
            for (var i = 0; i < tagsArr.length; i++) {
                if (i > 4) {
                    break;
                }
                html += '<span class="label label-warning">' + tagsArr[i] + '</span>';
            }
        } else {
            html = '暂无标签';
        }
        return html;
    },
    operation: function (value, row, index, field) {
        var html = '<button type="button" class="btn btn-default" onclick="contactDetail(\'' + row.contactId + '\')"><i class="mdi mdi-eye"></i>查看</button>';
        html += '<button type="button" class="btn btn-default" onclick="editContact(\'' + row.contactId + '\')"><i class="mdi mdi-pencil"></i>修改</button>';
        if (row.topContact == '1' || row.topContact == null) {   //常用 0 常用 1 不常用
            html += '<button type="button" data-stata="0" class="btn btn-default" onclick="searchCustomerPoolLists(this, \'' + row.contactId + '\')"><i class="mdi mdi-approval"></i>设为常用</button>';
        } else {
            html += '<button type="button" data-stata="1" class="btn btn-default btn-success" onclick="searchCustomerPoolLists(this, \'' + row.contactId + '\')"><i class="mdi mdi-check-circle-outline"></i>取消常用</button>';
        }
        return html;
    },
}

/**
 * 功能：跳转线上线下电话跟进
 * 参数：1-线上电话  2-拜访  3-微信  4-线下电话  5-邮箱  6-陪访
 * */
function goOnline(customerId, contactId, contactName, contactInformation, name) {
    var type = '';
    var title = '跟进';

    // 线上电话
    if (name == '线上电话') {
        type = "1";
        title = '联系人跟进-线上电话';
    }
    // 拜访
    if (name == '拜访') {
        type = "2";
        title = '联系人跟进-拜访';
    }
    // 微信
    if (name == '微信交流') {
        type = "3";
        title = '联系人跟进-微信交流';
    }
    // 线下电话
    if (name == '线下电话') {
        type = "4";
        title = '联系人跟进-线下电话';
    }
    // 电子邮件
    if (name == '电子邮件') {
        type = "5";
        title = '联系人跟进-电子邮件';
    }
    // 陪访
    if (name == '陪访') {
        type = "6";
        title = '联系人跟进-陪访';
    }
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: title,
        url: "/front/contactManager/user/contactFollow?type=" + type + "&bs=0" +
            "&customerId=" + customerId + "&contactId=" + contactId + "&contactName=" + contactName + "&contactInformation=" + contactInformation
    }, true);
}

function callCenter (customerId) {
    /*parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : "线上电话",
        url : "/front/callCenter"
    }, true);*/
    var contactPersonData = [];
    $.ajax({
        url: "/customerController/selectContacts?customerId=" + customerId,
        type: 'GET',
        datatype: 'json',
        async: false,
        success: function (data) {
            if (data) {
                if (data.code == '000000') {
                    contactPersonData = data.data;
                }
            }
        }
    });
    window.parent.callModal(customerId,contactPersonData,3);
}


// //防止表头与表格不对齐
// $(window).resize(function () {
//     $contactTableList.bootstrapTable('resetView');
// });


/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 职务
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contactPositionFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-success-light'>公司管理</span>";
    } else if (1 == value) {
        return "<span class='label label-yellow-light'>财务</span>";
    } else if (2 == value) {
        return "<span class='label label-yellow-light'>人力</span>";
    } else if (3 == value) {
        return "<span class='label label-yellow-light'>其他</span>";
    }
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    if (row.abolishState == 1) {
        return '<button type="button" id="followUp" class="btn btn-default" data-index="0">\n' +
            '<i class="mdi mdi-image-filter-tilt-shift"></i>跟进</button>' +
            '<a style="margin: 0 6px;" type="button" id="edit" class="btn btn-xs btn-default edit-btn" title="修改" data-toggle="tooltip" onclick=\'editContact("' + row.contactId + '")\'>' +
            '<i class="mdi mdi-pencil" style="padding-right: 6px;"></i>修改</a>';
    } else {
        return '<span style="color: #ccc;text-decoration: line-through;" >-</span>';
    }
}

/**
 * 联系人废止状态  1启动 2废止
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function abolishStateFormat(value, row, index) {
    var is_checked = '';
    if (value == null || value == undefined || value == 0) {
        return "-";
    } else if (value == 2) {
        is_checked = '';
    } else if (value == 1) {
        is_checked = 'checked="checked"';
    }
    var poolStateHtml = '<label class="lyear-switch switch-solid switch-success">' +
        '<input type="checkbox" id="abolishState' + row.contactId + '" ' + is_checked + '>' +
        '<span  onClick="updateAbolishState(\'' + row.contactId + '\', \'' + row.customerId + '\',\'' + row.contactName + '\',\'' + row.contactInformation + '\',\'' + value + '\')"></span>' +
        '</label>';
    return poolStateHtml;
}

/**
 * 开启/废止客户详情下联系人
 * @param contactId 联系人id
 * @param customerId 客户id
 * @param contactName 联系人姓名
 * @param contactInformation 联系方式
 * @param abolishState 废止状态  1启动 2废止
 */
function updateAbolishState(contactId, customerId, contactName, contactInformation, abolishState) {
    var abolishState = (abolishState == 1) ? 2 : 1; // 发送参数值跟当前参数值相反
    var confirmMessage = '';
    if (abolishState == 1) {
        confirmMessage = "确定启用联系人吗？";
    } else {
        confirmMessage = "确定废止联系人吗？";
    }

    $.alert({
        title: '提示',
        content: confirmMessage,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customer/updateAbolishState",
                        data: {
                            contactId: contactId,
                            customerId: customerId,
                            contactName: contactName,
                            contactInformation: contactInformation,
                            abolishState: abolishState
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $contactTableList.bootstrapTable('updateCellById', {
                                    id: contactId,
                                    field: 'abolishState',
                                    value: abolishState
                                });
                                // contactList();
                                $.alert('操作成功');
                            } else {
                                $contactTableList.bootstrapTable('updateCellById', {
                                    id: contactId,
                                    field: 'abolishState',
                                    value: abolishState
                                }); // 因开关点击后样式是变的，失败也重置下
                                $.alert(data.message);
                            }
                        },
                        error: function () {
                            $.alert('修改失败，请稍后再试!');
                            $contactTableList.bootstrapTable('updateCellById', {
                                id: contactId,
                                field: 'abolishState',
                                value: abolishState
                            }); // 因开关点击后样式是变的，失败也重置下
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                    if (abolishState == 1) {
                        $("#abolishState" + contactId).prop('checked', false);
                    } else {
                        $("#abolishState" + contactId).prop('checked', true);
                    }
                }
            }
        }
    });
}

/**
 * 联系人类型(在职 0  离职 1)
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function poolTypeFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-success-light'>在职</span>";
    } else if (1 == value) {
        return "<span class='label label-info-light'>离职</span>";
    }
}

/**
 * 目前意向(0有意向, 1无意向)
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function currentIntentionFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-success-light'>有意向</span>";
    } else if (1 == value) {
        return "<span class='label label-info-light'>无意向</span>";
    }
}

/**
 * 点击客户姓名跳转客户详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerNameFormat(value, row, index) {
    if (value == null) {
        value = '';
    }
    return '<a style="color:red;cursor:pointer;text-decoration:underline;" target="_blank"  onclick=\'customerDetail(\"' + row.customerId + '")\'>' + value + '</a>';
}

function customerDetail(customerId) {
    $.ajax({
        url: '/customerController/selectCustomerSelf',
        type: 'POST',
        dataType: "json",
        data: {
            "customerId" : customerId
        },
        success: (function (data) {
            if (data.code == "000000") {
                if(data.data == true) {
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '客户详情',
                        url: "/front/user/customerManager/customerDetail?customerId=" + customerId
                    }, true);
                }else{
                    $.alert("暂无权限查看该客户");
                }

            } else {
                $.alert("操作失败");
            }
        }),
        error: (function () {
            $.alert("失败");
        })
    });



}

/**
 * 点击联系人姓名跳转联系人详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contactNameFormat(value, row, index) {
    if (value == null) {
        value = '';
    }
    return '<a style="color:red;cursor:pointer;text-decoration:underline;" target="_blank"  onclick=\'contactDetail(\"' + row.contactId + '")\'>' + value + '</a>';
}

function contactDetail(contactId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '联系人详情',
        url: "/front/user/contactManager/contactDetail?type=admin&contactId=" + contactId
    }, true);
}


// 渲染城市列表
function getProvinceLxr() {
    let provinceNames = [];
    $.each(cityJson[0], function (key, value) {
        provinceNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#province').html(provinceNames.join(''));
    getCityLxr('110000')
}

// 根据省获取市
function getCityLxr(provinceId) {
    $('#city').html('');
    let key = '0,' + provinceId;
    let cityNames = [];
    $.each(cityJson[key], function (key, value) {
        cityNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#city').html(cityNames.join(''));
}

// '切换城市'
function changeCityLxr() {
    getCityLxr($('#province').val());
}

/**
 * 新增联系人
 */
function addContact() {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '新增联系人',
        url: "/front/contactManager/addContact?customerId=" + ""
    }, true);
}

/**
 * 新增联系方式
 */
function addContactInformation() {
    //获取当前行
    var row = $contactTableList.bootstrapTable('getSelections');
    if (row.length == 0 || row.length > 1) {
        $.alert("请选择一行数据后再操作");
    } else {
        //$.alert(row[0].contactId);
        parent.$(parent.document).data('multitabs').create({
            iframe: true,
            title: '新增联系方式',
            url: "/front/contactManager/addContactInformation?contactId=" + row[0].contactId + "&contactInformationBs=1" + "&customerId=" + row[0].customerId
        }, true);

    }
}

/**
 * 批量废止联系人
 */
function batchAbolition() {
    var idLists = [];
    var idList = $contactTableList.bootstrapTable('getAllSelections');

    if (idList.length == 0) {
        $.alert("请选择一行数据后再操作");
    } else {

        // for (var i = 0; i < idList.length; i++) {
        //     idLists.push(idList[i]);
        //     alert(idList[i].contactId);
        // }
    }

}

/**
 * 修改联系人
 */
function editContact(contactId) {

    $.ajax({
        url: '/contact/selectContactById',
        type: 'POST',
        dataType: "json",
        data: {
            contactId: contactId,
        },
        success: (function (data) {
            $('#editModel').modal('show');
            if (data.code == "000000") {
                $("#contactIdLxr").val(data.data.contactId);
                $("#customerIdLxr").val(data.data.customerId);
                $("#contactNatureLxr").val(data.data.contactNature);
                $("#contactNameLxr").val(data.data.contactName);                // 姓名
                $("#contactPositionLxr").val(data.data.contactPosition);        // 职务
                $("#onTheJobSituationLxr").val(data.data.onTheJobSituation);  //在职情况
                $("#contactInformationLxr").val(data.data.contactInformation);
                $("#mailBoxLxr").val(data.data.mailBox);  //wx
                $("#wxLxr").val(data.data.wx);  //微信
                $('#editModel select').selectpicker('refresh');
                //$("#contactState").val(data.data.contactState);  //联系人类型    主联系人-1   从联系人-2
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    })
}

/**
 * 提交修改联系人
 * */
function updateContact() {
    var contactId = $('#contactIdLxr').val(); //客户下联系人id
    var customerId = $('#customerIdLxr').val(); //客户下联系人id
    var contactNature = $('#contactNatureLxr').val(); //联系人性质  0企业联系人  1个人联系人
    var contactName = $('#contactNameLxr').val(); //联系人姓名
    var contactPosition = $('#contactPositionLxr').val();  //职务
    var contactInformation = $('#contactInformationLxr').val();  //联系方式
    var onTheJobSituation = $('#onTheJobSituationLxr').val();  //在职情况
    var wx = $('#wxLxr').val();  //微信
    var mailBox = $('#mailBoxLxr').val();  //邮箱
    var homeAddress = $('#homeAddressLxr').val();  //家庭住址
    var companyAddress = $('#companyAddressLxr').val();  //公司地址

    var jsonData = {
        contactId: contactId,
        contactName: contactName,  //联系人姓名
        contactPosition: contactPosition,  //职务
        contactInformation: contactInformation,  //联系方式
        onTheJobSituation: parseInt(onTheJobSituation),  //在职情况
        wx: wx,  //微信
        mailBox: mailBox,  //邮箱
        homeAddress : homeAddress, //家庭住址
        companyAddress: companyAddress, //公司地址
        customerId: customerId,
        contactNature : contactNature
    };

    $.ajax({
        url: '/customer/updateCustomerContactPerson',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $('#editModel').modal('hide');
                $contactTableList.bootstrapTable('refresh');
            } else {
                $.alert("操作失败");
            }
        }),
        error: (function () {
            $.alert("失败");
        })
    });


}

function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

var data = {};

// // 全部 本周 本月
function selectTime(time) {
    $('.selector-box dd a').removeClass('active');
    $('.selector-box dl dd:first-of-type a').addClass('active');

    $('.filter-content input').val('');
    $('.filter-content select').val('').selectpicker('refresh');//重置--高级筛选select框
    $('.reset-style input').val('');
    $('#contactCategory').val('全部联系人').selectpicker('refresh');//重置--高级筛选select框

    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    data = {
        pageIndex: 1,  //页码
        pageSize: 5,  //分页大小
        sortName: "createTm",  //排序列名字
        sortOrder: "desc",  //排序规则(asc/desc)
        bs: "0",  //标识  0管理端 1用户端
        dateType: $("#dateType").val()
    };
    $contactTableList.bootstrapTable('refreshOptions', {queryParams: queryParamsMoth});
}

/*function selectMore() {
    var dlDom = document.querySelectorAll('.selector-box dl');
    for (var i = 0; i < dlDom.length; i++) {
    }
}*/

// 超出一行展开
/*$(document).ready(function () {
    var preResult = $('.filter-box dd').height();
    var pre = $('.filter-box dl').height();

    $(".load-more").click(function () {
        if (!$(this).hasClass('active')) {
            $(this).parent().parent().animate({
                height: preResult
            });
            $(this).addClass('active');
        } else {
            $(this).parent().parent().animate({
                height: pre
            });
            $(this).removeClass('active');
        }
    });
});*/
// 行业渲染
$.ajax({
    url: "/contact/selectIndustry",
    async: true,
    data: {
        "bs": "0"  //标识  0管理端 1用户端
    },
    type: "POST",
    dataType: "json",
    success: function (data) {
        var html = ""
        for(var i = 0; i< data.data.length; i++){
            var codeId = data.data[i].code
            html += '<dd><a href="JavaScript:void(0);" onclick="searchCustomerPoolList(this, 0,' + codeId + ')"><span>' + data.data[i].name + '</span></a></dd>';
        }
        $(".selector-box .box1").append(html);

        var $dl = $('.selector-box .box1');
        var rowHeight = $dl.height();
        var moreBtn = '<dd class="more"><a href="JavaScript:void(0);"><i class="mdi mdi-chevron-double-down"></i>展开</a></dd>';
        if (rowHeight > 34) {
            $dl.addClass('row-more').append(moreBtn);
            $dl.on('click', 'dd.more', function () {
                if ($dl.hasClass('row-more')) {
                    $dl.removeClass('row-more').find('dd.more a').html('<i class="mdi mdi-chevron-double-up"></i>收起');
                } else {
                    $dl.addClass('row-more').find('dd.more a').html('<i class="mdi mdi-chevron-double-down"></i>展开');
                }
            });
        }

    }

})
// 地区渲染
$.ajax({
    url: "/contact/selectProvince",
    async: true,
    data: {
        "bs": "0"  //标识  0管理端 1用户端
    },
    type: "POST",
    dataType: "json",
    success: function (data) {
        var html = ""
        for(var i = 0;i<data.data.length;i++){
            var codeId = data.data[i].code
            html += '<dd><a href="JavaScript:void(0);" onclick="searchCustomerPoolList(this, 1,' + codeId + ')"><span>' + data.data[i].name + '</span></a></dd>';
        }
        $(".selector-box .box2").append(html);

        var $dl = $('.selector-box .box2');
        var rowHeight = $dl.height();
        var moreBtn = '<dd class="more"><a href="JavaScript:void(0);"><i class="mdi mdi-chevron-double-down"></i>展开</a></dd>';
        if (rowHeight > 34) {
            $dl.addClass('row-more').append(moreBtn);
            $dl.on('click', 'dd.more', function () {
                if ($dl.hasClass('row-more')) {
                    $dl.removeClass('row-more').find('dd.more a').html('<i class="mdi mdi-chevron-double-up"></i>收起');
                } else {
                    $dl.addClass('row-more').find('dd.more a').html('<i class="mdi mdi-chevron-double-down"></i>展开');
                }
            });
        }
    },
})
var commitData={
    "pageIndex": "1",  //页码
    "pageSize": "5",  //分页大小
    "sortName": "createTm",  //排序列名字
    "sortOrder": "desc",  //排序规则(asc/desc)
    "bs": "0",
    dateType: $("#dateType").val(),
    "provinceId": '', //省份id
    industry: '',  //行业
    currentIntention: '', //意向
    contactPosition: '', //职务
    onTheJobSituation: '', //在职情况
    month:''
}
function searchCustomerPoolList(_this, type, value) {
    var $this = $(_this);
    type !== (5 || 7 || 8) && $this.addClass('active').parent().siblings('dd').find('a').removeClass('active');
    $('.all').addClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $("#dateType").val("all");
    var data;
    if(type == (5 || 7 || 8)){
        $(".selector-box dl").find('dt').next().find('a').addClass('active').parent().siblings('dd').find('a').removeClass('active');
    }

    if (type === 5) {//普通条件查询
        data = {
            "pageIndex": "1",  //页码
            "pageSize": "5",  //分页大小
            "sortName": "createTm",  //排序列名字
            "sortOrder": "desc",  //排序规则(asc/desc)
            "bs": "0",  //标识  0管理端 1用户端
            "contactName": $('#contactName').val(),  //联系人姓名
            dateType: $("#dateType").val()
        };
        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.contactName=$('#contactName').val();
                params.bs=0;
                params.dateType=$("#dateType").val()
                return params;
            }
        });
    } else if (type == 6) {//高级搜索条件查询
        // $('#contactName').val("");
        data = {
            "pageIndex": "1",  //页码
            "pageSize": "5",  //分页大小
            "sortName": "createTm",  //排序列名字
            "sortOrder": "desc",  //排序规则(asc/desc)
            "bs": "0",  //标识  0管理端 1用户端
            customerName: $('#custName').val(), //客户名称
            contactInformation: $('#contactInformation').val(),//联系方式
            abolishState: $('#abolishState').val(), //废止状态  1启动 2废止
            dateType: $("#dateType").val()
        }

        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.customerName=$('#custName').val();
                params.contactInformation=$('#contactInformation').val()
                params.abolishState=$('#abolishState').val()
                params.bs=0;
                params.dateType=$("#dateType").val()
                return params;
            }
        });

    } else if (type == 1) {//按地区查询

        // data = {
        //     "pageIndex": "1",  //页码
        //     "pageSize": "5",  //分页大小
        //     "sortName": "createTm",  //排序列名字
        //     "sortOrder": "desc",  //排序规则(asc/desc)
        //     "bs": "1",  //标识  0管理端 1用户端
        //     "provinceId": value, //省份id
        //     dateType: $("#dateType").val()
        // }
        commitData.bs=1
        commitData.provinceId=value
        data=commitData

        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.bs=1;
                params.provinceId=value;
                params.dateType=$("#dateType").val()
                return params;
            }
        });

    } else if (type == 0) {//按行业查询

        // data = {
        //     "pageIndex": "1",  //页码
        //     "pageSize": "5",  //分页大小
        //     "sortName": "createTm",  //排序列名字
        //     "sortOrder": "desc",  //排序规则(asc/desc)
        //     "bs": "0",  //标识  0管理端 1用户端
        //     industry: value,  //行业
        //     dateType: $("#dateType").val()
        // }
        commitData.industry=value
        data=commitData

        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.bs=0;
                params.industry=value;
                params.dateType=$("#dateType").val()
                return params;
            }
        });
    } else if (type == 2) {//按意向查询
        // data = {
        //     "pageIndex": "1",  //页码
        //     "pageSize": "5",  //分页大小
        //     "sortName": "createTm",  //排序列名字
        //     "sortOrder": "desc",  //排序规则(asc/desc)
        //     "bs": "0",  //标识  0管理端 1用户端
        //     currentIntention: value, //意向
        //     dateType: $("#dateType").val()
        // }
        commitData.currentIntention=value
        data=commitData
        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.bs=0;
                params.currentIntention=value;
                params.dateType=$("#dateType").val()
                return params;
            }
        });
    } else if (type == 3) {//按职务查询
        // data = {
        //     "pageIndex": "1",  //页码
        //     "pageSize": "5",  //分页大小
        //     "sortName": "createTm",  //排序列名字
        //     "sortOrder": "desc",  //排序规则(asc/desc)
        //     "bs": "0",  //标识  0管理端 1用户端
        //     contactPosition: value, //职务
        //     dateType: $("#dateType").val()
        // }
        commitData.contactPosition=value
        data=commitData
        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.bs=0;
                params.contactPosition=value;
                params.dateType=$("#dateType").val()
                return params;
            }
        });
    } else if (type == 4) {//按在职情况查询
        // data = {
        //     "pageIndex": "1",  //页码
        //     "pageSize": "5",  //分页大小
        //     "sortName": "createTm",  //排序列名字
        //     "sortOrder": "desc",  //排序规则(asc/desc)
        //     "bs": "0",  //标识  0管理端 1用户端
        //     onTheJobSituation: value, //在职情况
        //     dateType: $("#dateType").val()
        // }
        commitData.onTheJobSituation=value
        data=commitData
        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.bs=0;
                params.onTheJobSituation=value;
                params.dateType=$("#dateType").val()
                return params;
            }
        });
    } else if (type == 7) {
        data = {//可用作废
            "pageIndex": "1",  //页码
            "pageSize": "5",  //分页大小
            "sortName": "createTm",  //排序列名字
            "sortOrder": "desc",  //排序规则(asc/desc)
            "bs": "0",  //标识  0管理端 1用户端
            dateType: $("#dateType").val(),
            abolishState: value, //废止状态  1启动 2废止
        }
        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.bs=0;
                params.abolishState=value;
                params.dateType=$("#dateType").val()
                return params;
            }
        });
    } else if (type == 8) { // 常用不常用
        data = {
            "pageIndex": "1",  //页码
            "pageSize": "5",  //分页大小
            "sortName": "createTm",  //排序列名字
            "sortOrder": "desc",  //排序规则(asc/desc)
            "bs": "0",  //标识  0管理端 1用户端
            dateType: $("#dateType").val(),
            topContact: value,//常用 0常用 1不常用
        }
        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.bs=0;
                params.topContact=value;
                params.dateType=$("#dateType").val()
                return params;
            }
        });
    } else if (type == 9) { // 常用不常用
        var monthParams = '';
        var dateTypeParams = '';
        if (value != '') {
            dateTypeParams = 'thisYearMonth'
        }
        value && (monthParams = year + '-' + value);
        // data = {
        //     "pageIndex": "1",  //页码
        //     "pageSize": "5",  //分页大小
        //     "sortName": "createTm",  //排序列名字
        //     "sortOrder": "desc",  //排序规则(asc/desc)
        //     "bs": "0",  //标识  0管理端 1用户端
        //     dateType: dateTypeParams,
        //     month: monthParams,//常用 0常用 1不常用
        // }
        commitData.dateType=dateTypeParams
        commitData.month=monthParams
        data=commitData
        $contactTableList.bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.bs=0;
                params.month=dateTypeParams;
                params.dateType=dateTypeParams
                return params;
            }
        });
    }

    // $contactTableList.bootstrapTable('refreshOptions', {queryParams: data});

}
/*function contactList(data) {
    $.ajax({
        url: "/contact/contactList",
        async: true,
        data: data,
        type: "POST",
        dataType: "json",
        success: function (data) {
            var html2 = ""
            for (var i = 0; i < data.data.length; i++) {
                var idcl = data.data[i].contactId;
                var idclTwo = data.data[i].customerId;
                var contactName = data.data[i].contactName;
                var contactInformation = data.data[i].contactInformation;
                html2 += `
<div id="boxBig">
            <div class="Contant">
                <div class="imageBox"><img style="width: 100px;height: 100px;border-radius: 50%;" src="${data.data[i].accessUrl}"></div>
                <div style="margin-left: 100px">
                    <div style="cursor: pointer" class="titleBox" onclick="contactDetail('` + idcl + `')">${data.data[i].contactName}</div>
                    <div class="leftRightBox">
                        <div class="companyBox">
                             <span style="color:red;cursor: pointer" onclick="customerDetail('` + idclTwo + `')">${data.data[i].customerName}</span>
                            <span id="vipCon">vip</span>
                            <span style="padding-left: 40px">职位：${data.data[i].contactPosition}</span>
                        </div>
                        <div class="companyBoxTwo">
                             <span target="_blank"  onclick="contactDetail('` + idcl + `')"><i class="mdi mdi-eye" title="查看详情"></i></span>
                             <span  onclick="searchCustomerPoolLists('` + idcl + `','0')" title="设置为常用联系人">🎗</span>
                             <span id="edit" data-toggle="tooltip" onclick="editContact('` + idcl + `')" title="修改"><i class="mdi mdi-pencil"></i></span>
                        </div>
                    </div>
                    <div class="restBox">
                        <span>线上电话</span>
                        <!--<span onclick="goOnline('\`+idclTwo+\`','\`+idcl+\`','\`+contactName+\`','\`+contactInformation+\`','\\线上电话\\')">线上电话</span>-->
                        <span onclick="goOnline('` + idclTwo + `','` + idcl + `','` + contactName + `','` + contactInformation + `','\拜访\')">拜访</span>
                        <span onclick="goOnline('` + idclTwo + `','` + idcl + `','` + contactName + `','` + contactInformation + `','\微信交流\')">微信交流</span>
                        <span onclick="goOnline('` + idclTwo + `','` + idcl + `','` + contactName + `','` + contactInformation + `','\线下电话\')">线下电话</span>
                        <span onclick="goOnline('` + idclTwo + `','` + idcl + `','` + contactName + `','` + contactInformation + `','\电子邮件\')">电子邮件</span>
                        <span onclick="goOnline('` + idclTwo + `','` + idcl + `','` + contactName + `','` + contactInformation + `','\陪访\')">陪访</span>
                    </div>
                </div>
                </div>
            </div>`
            }
            $("#boxBig").html(html2)
        },
        error: function (err) {
        }
    })
}*/

// 设置为常用联系人
function searchCustomerPoolLists(_this, contactId) {
    var $this = $(_this);
    var $stata = $this.data('stata');
    $.ajax({
        url: "/contact/setUpTopContact",
        async: true,
        data: {
            contactId: contactId,
            topContact: $stata, //常用 0常用 1不常用
        },
        type: "POST",
        dataType: "json",
        success: function (data) {
            if (data.code == "000000") {
                $stata = Number(!$stata);
                $this.data('stata', $stata);
                if ($stata) {
                    $this.addClass('btn-success').html('<i class="mdi mdi-check-circle-outline"></i>取消常用');
                } else {
                    $this.removeClass('btn-success').html('<i class="mdi mdi-approval"></i>设为常用');
                }
            } else {
                $.alert("操作失败");
            }
        }
    })

}



// 重置
$('#btn-reset').on('click', function () {
    $('.filter-content input').val('');

    $('.filter-content select').val('').selectpicker('refresh');//重置--高级筛选select框
    $('.reset-style input').val('');
    $('#contactCategory').val('全部联系人').selectpicker('refresh');//重置--高级筛选select框
    resetBanner()
    $contactTableList.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
});
function resetBanner(){
    $('.all').addClass('active-second');//全部
    $('.week').removeClass('active-second');//本周
    $('.month').removeClass('active-second');//本月
    $("#dateType").val("all");
}